package com.besall.allbase.view.activity.chipstoollevel4.findmy;

import static com.bes.bessdk.BesSdkConstants.BES_CONNECT_ERROR;
import static com.bes.bessdk.BesSdkConstants.BesConnectState;
import static com.bes.bessdk.BesSdkConstants.BES_CONNECT_SUCCESS;
import static com.bes.bessdk.BesSdkConstants.BES_WIFI_CHARACTERISTIC_RX_UUID;
import static com.bes.bessdk.BesSdkConstants.BES_WIFI_CHARACTERISTIC_TX_UUID;
import static com.bes.bessdk.BesSdkConstants.BES_WIFI_DESCRIPTOR_UUID;
import static com.bes.bessdk.BesSdkConstants.BES_WIFI_SERVICE_UUID;
import static com.bes.bessdk.BesSdkConstants.BesConnectState.BES_CONNECT;
import static com.besall.allbase.bluetooth.BluetoothConstants.Scan.BES_SCAN_RESULT;
import static com.besall.allbase.bluetooth.service.FindMy.FindMyConstants.BES_WATCH_ACTIVATE_PHONE;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Vibrator;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bes.bessdk.BesSdkConstants;
import com.bes.bessdk.connect.BleConnector;
import com.bes.bessdk.scan.BtHeleper;
import com.bes.bessdk.service.base.BesServiceConfig;
import com.bes.bessdk.service.base.BesServiceListener;
import com.bes.bessdk.utils.ArrayUtil;
import com.bes.bessdk.utils.SPHelper;
import com.bes.sdk.device.HmDevice;
import com.bes.sdk.utils.DeviceProtocol;
import bb.lanxing.R;
import com.besall.allbase.bluetooth.BluetoothConstants;
import com.besall.allbase.common.utils.ActivityUtils;
import com.besall.allbase.view.base.BaseActivity;


/**
 * @author ericshen
 * @time $ $
 */
public class FindMyActivity extends BaseActivity<IFindMyActivity, FindMyPresenter> implements IFindMyActivity, BesServiceListener, View.OnClickListener
{
    private static FindMyActivity instance;

    BluetoothDevice mDevice;
    HmDevice mHmDevice;
    BesServiceConfig mServiceConfig;

    private Button pickDevice;
    private Button connect_device;
    private Button send_data;
    private TextView ble_name;
    private Button stop_vibrate;

    private Vibrator vibrator;

    @Override
    protected FindMyPresenter createPresenter() {
        return new FindMyPresenter();
    }

    @Override
    protected void initBeforeSetContent() {
        mServiceConfig = new BesServiceConfig();
        mServiceConfig.setServiceUUID(BES_WIFI_SERVICE_UUID);
        mServiceConfig.setCharacteristicsUUID(BES_WIFI_CHARACTERISTIC_TX_UUID);
        mServiceConfig.setDescriptorUUID(BES_WIFI_DESCRIPTOR_UUID);
        mServiceConfig.setTotaConnect(false);
        mServiceConfig.setDeviceProtocol(DeviceProtocol.PROTOCOL_BLE);

        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_findmy;
    }

    @Override
    protected void bindView() {
        pickDevice = (Button)findViewById(R.id.pick_device);
        connect_device = (Button)findViewById(R.id.connect_device);
        send_data = (Button)findViewById(R.id.send_data);
        ble_name = (TextView)findViewById(R.id.ble_name);
        stop_vibrate = (Button)findViewById(R.id.stop_vibrate);
    }

    @Override
    protected void initView() {
        String titleStr = "FIND MY";
        tv_title.setText(titleStr);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        pickDevice.setOnClickListener(instance);
        connect_device.setOnClickListener(instance);
        send_data.setOnClickListener(instance);
        stop_vibrate.setOnClickListener(instance);
    }

    @Override
    protected void setInstance() {
        instance = this;
    }

    @Override
    protected void removeInstance() {
        instance = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mPresenter.disconnect();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == BluetoothConstants.Scan.REQUEST_CODE_SCAN) {
            onPickDevice(resultCode, data);
        }
    }

    private void onPickDevice(int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            mHmDevice = (HmDevice) data.getSerializableExtra(BES_SCAN_RESULT);
            mDevice = BtHeleper.getBluetoothAdapter(instance).getRemoteDevice(mHmDevice.getPreferredProtocol() == DeviceProtocol.PROTOCOL_BLE ? mHmDevice.getBleAddress() : mHmDevice.getDeviceMAC());

            mServiceConfig.setDevice(mHmDevice);
            BesConnectState state = BleConnector.getsConnector(instance, null, null).getDeviceConnectState(mServiceConfig);
            if (state == BES_CONNECT) {
                ble_name.setTextColor(Color.GREEN);
                mPresenter.connectDevice(mServiceConfig, instance, instance);
            } else {
                ble_name.setTextColor(Color.DKGRAY);
            }
            ble_name.setText(mDevice.getName());
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(item.getItemId() == android.R.id.home){
            finish();
        }

/*        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }*/
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
    	
			 if(v.getId() == R.id.pick_device){
			    	 mPresenter.pickDecice(instance, BluetoothConstants.Scan.SCAN_BLE);
			 }else if(v.getId() == R.id.connect_device){
			     if (mHmDevice == null) {
			         ActivityUtils.showToast(R.string.pleaseSelectDevice);
			         return;
			     }
			     mServiceConfig.setDevice(mHmDevice);
			     mPresenter.connectDevice(mServiceConfig, instance, instance);
			 }else if(v.getId() == R.id.send_data){
				 mPresenter.sendFindMyData();
			 }else if(v.getId() == R.id.stop_vibrate){
			     if (vibrator != null) {
			         vibrator.cancel();
			     }
			 }
			    	
    	
/*        switch (v.getId()) {
            case R.id.pick_device:
                mPresenter.pickDecice(instance, BluetoothConstants.Scan.SCAN_BLE);
                break;
            case R.id.connect_device:
                if (mHmDevice == null) {
                    ActivityUtils.showToast(R.string.pleaseSelectDevice);
                    return;
                }
                mServiceConfig.setDevice(mHmDevice);
                mPresenter.connectDevice(mServiceConfig, instance, instance);
                break;
            case R.id.send_data:
                mPresenter.sendFindMyData();
                break;
            case R.id.stop_vibrate:
                if (vibrator != null) {
                    vibrator.cancel();
                }
                break;
            default:
                break;
        }*/
    }

    @Override
    public void onTotaConnectState(boolean state, HmDevice hmDevice) {

    }

    @Override
    public void onErrorMessage(int msg, HmDevice hmDevice) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ble_name.setTextColor(Color.RED);
                showToast(R.string.connect_failed);
            }
        });
    }

    @Override
    public void onStateChangedMessage(int msg, String msgStr, HmDevice hmDevice) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (msg == BES_CONNECT_SUCCESS) {
                    ble_name.setTextColor(instance.getResources().getColor(R.color.green));
                    showToast(R.string.connect_success);
                } else if (msg == BES_CONNECT_ERROR) {
                    ble_name.setTextColor(Color.RED);
                    showToast(R.string.connect_failed);
                } else if (msg == BES_WATCH_ACTIVATE_PHONE) {
                    long[] pattern = {200, 2000, 2000, 200, 200, 200};
                    vibrator.vibrate(pattern, 0);
                }
            }
        });
    }

    @Override
    public void onSuccessMessage(int msg, HmDevice hmDevice) {

    }

    protected void showToast(int msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    protected void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

}
